package com.coship.vas.dapg.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.ehcache.Cache;

import org.springframework.stereotype.Repository;

import com.coship.vas.dapg.contans.PrgrelationContants;
import com.coship.vas.dapg.entity.Prgrelation;
import com.coship.vas.dapg.service.RelationService;
import com.coship.vas.dapg.util.SysCacheUtil;

@Repository("prgrelationService")
public class PrgrelationServiceImpl implements RelationService {
    /**
     * params 传递参数
     */
    @Override
    public List<Prgrelation> getPrgrelation(Map<String, String> params) throws Exception {
        List<Prgrelation> list = new ArrayList<Prgrelation>();
        String prg_id = params.get(PrgrelationContants.REQUEST_PID); // 节目ID
        String descLen = params.get(PrgrelationContants.REQUEST_DESC_LEN);// 节目简介长度
        String imageScale = params.get(PrgrelationContants.REQUEST_IMAGE_SCALE);
        String imageSize = params.get(PrgrelationContants.REQUEST_IMAGE_SIZE);
        String maxCount = params.get(PrgrelationContants.REQUEST_MAX_COUNT);

        StringBuilder sb = new StringBuilder();
        sb.append(PrgrelationContants.CACHE_KEY_PREFIX).append(prg_id).append(PrgrelationContants.CACHE_KEY_SEPARATOR)
                .append(descLen);
        sb.append(PrgrelationContants.CACHE_KEY_SEPARATOR).append(imageScale).append(
                PrgrelationContants.CACHE_KEY_SEPARATOR).append(imageSize).append(
                PrgrelationContants.CACHE_KEY_SEPARATOR).append(maxCount);
        String keyStr = sb.toString();
        // 以节目ID_descLen_imageScale_imageSize_maxCount作为缓存key
        Cache cache = SysCacheUtil.getCache(PrgrelationContants.PRG_CACHE_NAME);
        net.sf.ehcache.Element element = cache.get(keyStr);
        if (element == null) {
            try {
                list = ProcessRelation.xmlToBean(params, PrgrelationContants.METHODNAME);
                if (!list.isEmpty()) {
                    element = SysCacheUtil.set(keyStr, list);
                } else {
                    return list;
                }
            } catch (Exception e) {
                element = null;
                throw e;
            }
        }
        return (List<Prgrelation>) element.getObjectValue();
    }
}
